package com.sczfdf.www.sda.gov.cn.modo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sczfdf.www.sda.gov.cn.App;
import com.sczfdf.www.sda.gov.cn.tool.IsJson;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.model.AfterExtractor;
import us.codecraft.webmagic.model.HttpRequestBody;
import us.codecraft.webmagic.model.annotation.TargetUrl;
import us.codecraft.webmagic.utils.HttpConstant;

@TargetUrl("[0-9A-Za-z\\.://\\?]+=getBaNewInfoPage")
public class PageDO implements AfterExtractor {

	@Override
	public void afterProcess(Page page) {
		if (!IsJson.getJSONType(page.getRawText())) {
			pageRetry(page);
			return;
		}
		JSONObject parseObject = JSONObject.parseObject(page.getRawText());
		//		if (parseObject == null || parseObject.getJSONArray("list").size() <=1) {
		//			pageRetry(page);
		//			return;
		//		}

		Integer pageNumber = parseObject.getInteger("pageNumber");
		if(App.isSetRequest) {
			synchronized (this) {
				if(App.isSetRequest) {
					for (int i=1; i<40000; i++) {
						page.addTargetRequest(createRequest(i));
					}
				}
			}
			App.isSetRequest = false;
			System.err.println(page.getTargetRequests().size());
		}else {
			JSONArray jsonArray = parseObject.getJSONArray("list");
			List<String> list = new ArrayList<String>();

			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				list.add(jsonObject.getString("newProcessid"));
			}

			//				if (this.pageNumber < this.pageCount) {
			//					page.addTargetRequest(PageDO.createRequest(pageNumber+1));
			//				}
			for (String newProcessid : list) {
				page.addTargetRequest(GovDO.createRequest(newProcessid));
				page.addTargetRequest(GovImageDO.createRequest(newProcessid));
			}
			System.err.println("页数: " + pageNumber);
		}
	}

	private void pageRetry(Page page) {
		HttpRequestBody requestBody = page.getRequest().getRequestBody();
		String string = new String(requestBody.getBody());
		Matcher matcher = Pattern.compile("page=[0-9]+").matcher(string);
		matcher.find();
		Matcher matcher2 = Pattern.compile("[0-9]+").matcher(matcher.group());
		matcher2.find();

		int parseInt = Integer.parseInt(matcher2.group());
		page.addTargetRequest(createRequest(parseInt));
		System.out.println("page重试: " + (parseInt));
		//		try {
		//			Thread.sleep(1000);
		//		} catch (InterruptedException e) {
		//			e.printStackTrace();
		//		}
	}

	//备用
	{
		//		JSONObject parseObject = JSONObject.parseObject(page.getRawText());
		//		Integer pageNumber = parseObject.getInteger("pageNumber");
		//
		//		if(parseObject.getInteger("pageCount") > pageNumber)
		//			page.addTargetRequest(createIniRequest(pageNumber+1));
		//
		//		JSONArray jsonArray = parseObject.getJSONArray("list");
		//		List<String> list = new ArrayList<String>();
		//		for (int i = 0; i < jsonArray.size(); i++) {
		//			JSONObject jsonObject = jsonArray.getJSONObject(i);
		//			list.add(jsonObject.getString("newProcessid"));
		//		}
		//
		//		for (String newProcessid : list) {
		//			page.addTargetRequest(GovDO.createRequest(newProcessid));
		//		}
	}

	public static Request createRequest(Integer page) {
		Request request = new Request("http://125.35.6.80:8080/ftba/itownet/fwAction.do?method=getBaNewInfoPage");

		Map<String, Object> params = new HashMap<>();
		params.put("applyname", "");
		params.put("applysn", "");
		params.put("conditionType", "1");
		params.put("on", "true");
		params.put("page", page);
		params.put("pageSize", "15");
		params.put("productName", "");
		request.setRequestBody(HttpRequestBody.form(params, "utf-8"));
		request.setMethod(HttpConstant.Method.POST);

		//		request.addCookie("Cookie", "JSESSIONID=811F969DF04B847F3125FCF86322FE93");

		request.addHeader("Cookie", "JSESSIONID=B7360A2DDEBB8AFE290802F00084CC03");
		request.addHeader("Accept", "*/*");
		request.addHeader("Accept-Encoding", "gzip, deflate");
		request.addHeader("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
		request.addHeader("Cache-Control", "no-cache");
		request.addHeader("Connection", "keep-alive");
		//		request.addHeader("Content-Length", "75");
		request.addHeader("Content-Type", "application/x-www-form-urlencoded;utf-8");
		request.addHeader("Host", "125.35.6.80:8080");
		request.addHeader("Pragma", "no-cache");
		request.addHeader("Referer", "http://125.35.6.80:8080/ftba/fw.jsp");
		request.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13) AppleWebKit/603.1.13 (KHTML, like Gecko) Version/10.1 Safari/603.1.13");
//		request.addHeader("User-Agent", UserAgentTool.getUserAgent());
		request.addHeader("X-Requested-With", "XMLHttpRequest");

		request.setPriority(Long.MAX_VALUE);

		return request;
	}

	//	@ExtractBy(value="$.list..newProcessid", type=Type.JsonPath, notNull=true)
	//	private List<String> list = new ArrayList<String>();
	////	@ExtractBy(value="$.pageCount", type=Type.JsonPath)
	//	private Integer pageCount;
	////	@ExtractBy(value="$.pageSize", type=Type.JsonPath)
	//	private Integer pageSize;
	////	@ExtractBy(value="$.totalCount", type=Type.JsonPath)
	//	private Integer totalCount;
	////	@ExtractBy(value="$.pageNumber", type=Type.JsonPath)
	//	private Integer pageNumber;

	//	public List<String> getList() {
	//		return list;
	//	}
	//	public void setList(List<String> list) {
	//		this.list = list;
	//	}
	//	public Integer getPageCount() {
	//		return pageCount;
	//	}
	//	public void setPageCount(Integer pageCount) {
	//		this.pageCount = pageCount;
	//	}
	//	public Integer getPageSize() {
	//		return pageSize;
	//	}
	//	public void setPageSize(Integer pageSize) {
	//		this.pageSize = pageSize;
	//	}
	//	public Integer getTotalCount() {
	//		return totalCount;
	//	}
	//	public void setTotalCount(Integer totalCount) {
	//		this.totalCount = totalCount;
	//	}
	//	public Integer getPageNumber() {
	//		return pageNumber;
	//	}
	//	public void setPageNumber(Integer pageNumber) {
	//		this.pageNumber = pageNumber;
	//	}
	//	@Override
	//	public String toString() {
	//		return "PageDO [list=" + list + ", pageCount=" + pageCount + ", pageSize=" + pageSize + ", totalCount="
	//				+ totalCount + ", pageNumber=" + pageNumber + "]";
	//	}
}
